package jh.com.jhappbf.unload;

import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;

import com.ab.activity.AbActivity;
import com.ab.fragment.AbDialogFragment;
import com.ab.model.AbMenuItem;
import com.ab.util.AbDialogUtil;
import com.ab.util.AbToastUtil;
import com.ab.view.pullview.AbPullToRefreshView;
import com.ab.view.titlebar.AbTitleBar;
import com.android.volley.Request.Priority;
import com.android.volley.Response.ErrorListener;
import com.android.volley.Response.Listener;
import com.yzq.zxinglibrary.android.CaptureActivity;
import com.yzq.zxinglibrary.common.Constant;

import org.json.JSONObject;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import androidx.core.content.ContextCompat;
import jh.com.jhappbf.R;
import jh.com.jhappbf.httputils.VolleyCallWebService;
import jh.com.jhappbf.httputils.VolleySingleton;
import jh.com.jhappbf.ui.State;
import jh.com.jhappbf.utils.JsonHelper;
import jh.com.jhappbf.verify.ListPopAdapter;
import jh.com.jhappbf.view.PointDialog;

/**
 * @author Administrator
 */
public class UnloadQuery extends AbActivity {
    private View mContentView;
    private View mNetErrorView;
    private Context mAppContext;
    private AbPullToRefreshView mPullToRefreshListView;
    private ListView mListView;
    private MyBaseAdapter mAdapter;
    private Button mTryAgain;
    private int mCurrentPage = 1;
    private final int mPageSize = 30;
    private List<JSONObject> mData;
    private AbDialogFragment mDialogFragment;
    private AbTitleBar mAbTitleBar;
    private EditText mSelectEdit;
    private Button mSelectBtn;
    private String mType;//成功失败的类型

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        mContentView = getLayoutInflater().inflate(R.layout.query_pullrefresh_list_view, null);
        mNetErrorView = getLayoutInflater().inflate(R.layout.net_error_activity, null);
        setAbContentView(mContentView);
        mType=getIntent().getStringExtra("mType");
        mAbTitleBar = this.getTitleBar();
        mAbTitleBar.setTitleFullWidth();
        mAbTitleBar.setLogo(R.drawable.button_selector_back);
        mAbTitleBar.setTitleBarBackgroundColor(ContextCompat.getColor(this, R.color.orange));
        mAbTitleBar.setTitleTextMargin(10, 0, 10, 0);
        mAbTitleBar.setLogoLine(R.mipmap.line);
        mAppContext = getApplicationContext();
        initView();
    }

    /**
     * 初始化
     */
    private void initView() {
        mPullToRefreshListView = mContentView.findViewById(R.id.verify_pullToRefreshView);
        mListView = mContentView.findViewById(R.id.verify_query_listView);
        mSelectEdit=mContentView.findViewById(R.id.select_edit);
        mSelectBtn=mContentView.findViewById(R.id.query_btn);
        mSelectBtn.setOnClickListener(v -> loaFirst());

        mData = new ArrayList<>();
        mAdapter = new MyBaseAdapter();
        mListView.setAdapter(mAdapter);
        mTryAgain = mNetErrorView.findViewById(R.id.network_error_btn);
        mPullToRefreshListView.setOnHeaderRefreshListener(arg0 -> loaFirst());

        mPullToRefreshListView.setOnFooterLoadListener(arg0 -> loadMore());

        mTryAgain.setOnClickListener(v -> {
            setAbContentView(mContentView);
            refresh();
        });

        mListView.setOnItemClickListener((parent, view, position, id) -> {

        });

        setDropList();
        refresh();
    }

    /**
     * 设置标题下拉列表
     */
    private void setDropList() {
        mAbTitleBar.setTitleTextBackgroundResource(R.drawable.drop_down_selector);
        View v = getLayoutInflater().inflate(R.layout.list_pop, null);
        final ListView listView = v.findViewById(R.id.pop_list);
        final List<AbMenuItem> data = new ArrayList<>();
        if (TextUtils.equals("成功",mType)){
            data.add(new AbMenuItem("回传成功"));
        }else  if (TextUtils.equals("失败",mType)){
            data.add(new AbMenuItem("回传失败"));
        }else {
            data.add(new AbMenuItem("回传成功"));
            data.add(new AbMenuItem("回传失败"));
            data.add(new AbMenuItem("未回传"));
        }


        ListPopAdapter mListPopAdapter = new ListPopAdapter(this, data, R.layout.item_list_pop);
        listView.setAdapter(mListPopAdapter);
        mAbTitleBar.setTitleTextDropDown(v);
        mAbTitleBar.setTitleText(data.get(0).getText());
        listView.setOnItemClickListener((parent, view, position, id) -> {
            mAbTitleBar.setTitleText(data.get(position).getText());
            mAbTitleBar.hideWindow();
            refresh();
        });
    }

    /**
     * 刷新和第一次加载
     */
    private void refresh() {
        mDialogFragment = AbDialogUtil.showLoadDialog(this, R.mipmap.ic_load,
                "加载中,请稍等...");
        mDialogFragment.setCancelable(false);
        mDialogFragment.setAbDialogOnLoadListener(this::loaFirst);
    }


    /**
     * 第一次加载数据
     */
    private void loaFirst() {
        mCurrentPage = 1;
        String methodName = "queryUnloadSaver";
        ArrayList<String> params = new ArrayList<>();
        ArrayList<String> values = new ArrayList<>();
        params.add("strCurrentPage");
        params.add("strPageSize");
        params.add("isCommit");
        params.add("select");
        params.add("company");
        params.add("userName");
        params.add("mType");
        values.add(Integer.toString(mCurrentPage));
        values.add(Integer.toString(mPageSize));
        String selectOperate = mAbTitleBar.getTitleTextButton().getText().toString().trim();
        if (TextUtils.equals("回传成功",selectOperate)){
            values.add("1");
        }else if (TextUtils.equals("回传失败",selectOperate)){
            values.add("2");
        }else {
            values.add("0");
        }
        values.add(mSelectEdit.getText().toString().trim());
        values.add(State.mCompanyName);
        values.add(State.mAccount);
        values.add(mType);
        Listener<String> listener = response -> {
            AbDialogUtil.removeDialog(UnloadQuery.this);
            mPullToRefreshListView.onHeaderRefreshFinish();
            mData.clear();
            List<JSONObject> newListData = JsonHelper.getJsonObjects(response);
            if (newListData.size() > 0) {
                mData.addAll(newListData);
                mCurrentPage++;
                mAdapter.notifyDataSetChanged();
            }
        };

        ErrorListener errorListener = error -> {
            AbDialogUtil.removeDialog(UnloadQuery.this);
            mPullToRefreshListView.onHeaderRefreshFinish();
            setAbContentView(mNetErrorView);
        };

        VolleyCallWebService webService = new VolleyCallWebService(methodName,
                params, values, listener, errorListener, Priority.NORMAL);
        VolleySingleton.getVolleyInstance(mAppContext).addRequest(webService);
    }


    /**
     * 加载更多
     */
    private void loadMore() {
        String methodName = "queryUnloadSaver";
        ArrayList<String> params = new ArrayList<>();
        ArrayList<String> values = new ArrayList<>();
        params.add("strCurrentPage");
        params.add("strPageSize");
        params.add("isCommit");
        params.add("select");
        params.add("company");
        params.add("userName");
        params.add("mType");

        values.add(Integer.toString(mCurrentPage));
        values.add(Integer.toString(mPageSize));
        String selectOperate = mAbTitleBar.getTitleTextButton().getText().toString().trim();
        if (TextUtils.equals("回传成功",selectOperate)){
            values.add("1");
        }else if (TextUtils.equals("回传失败",selectOperate)){
            values.add("2");
        }else {
            values.add("0");
        }
        values.add(mSelectEdit.getText().toString().trim());
        values.add(State.mCompanyName);
        values.add(State.mAccount);
        values.add(mType);
        Listener<String> listener = response -> {
            AbDialogUtil.removeDialog(UnloadQuery.this);
            mPullToRefreshListView.onFooterLoadFinish();
            List<JSONObject> newListData = JsonHelper.getJsonObjects(response);
            if (newListData != null && newListData.size() > 0) {
                mData.addAll(newListData);
                mCurrentPage++;
                mAdapter.notifyDataSetChanged();
            }
        };

        ErrorListener errorListener = error -> {
            AbDialogUtil.removeDialog(UnloadQuery.this);
            mPullToRefreshListView.onFooterLoadFinish();
            setAbContentView(mNetErrorView);
        };

        VolleyCallWebService webService = new VolleyCallWebService(methodName,
                params, values, listener, errorListener, Priority.NORMAL);
        VolleySingleton.getVolleyInstance(mAppContext).addRequest(webService);
    }
    @Override
    public void onBackPressed() {
        finish();
    }

    class MyBaseAdapter extends BaseAdapter {
        @Override
        public int getCount() {
            return mData.size();
        }

        @Override
        public Object getItem(int position) {
            return mData.get(position);
        }

        @Override
        public long getItemId(int position) {
            return position;
        }

        @Override
        public View getView(int position, View convertView, ViewGroup parent) {
            ViewHolder holder;
            if (convertView == null) {
                convertView = View.inflate(UnloadQuery.this,R.layout.list_view_item_txt, null);
                holder = new ViewHolder();
                holder.txt = convertView.findViewById(R.id.list_view_item_txt);
                convertView.setTag(holder);
            } else {
                holder = (ViewHolder) convertView.getTag();
            }
            String symbol = "\r\n";
            JSONObject obj = mData.get(position);
            String builder = "单号:" +
                    obj.optString("ContractId") +
                    symbol +
                    "行号:" +
                    obj.optString("LineNumber") +
                    symbol +
                    "过磅单号:" +
                    obj.optString("saverid") +
                    symbol +
                    "数量:" +
                    obj.optString("number") +
                    symbol +
                    "库存地点:" +
                    obj.optString("stockAdress") +
                    symbol +
                    "批号:" +
                    obj.optString("batchNumber") +
                    symbol +
                    "单位:" +
                    obj.optString("unit")+
                    symbol +
                    "时间:" +
                    obj.optString("sdatetime")+
                    symbol +
                    "结果:" +
                    obj.optString("S2");
            holder.txt.setText(builder);
            return convertView;
        }
    }

    class ViewHolder {
        public TextView txt;
    }


}
